package com.goalias.util;

import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;
import java.util.regex.Pattern;

/**
 * XssCleanRuleUtils
 * 优化考虑：
 * 1、增加是否开启Xss防护开关配置（默认开启，对外压力测试关闭）
 * 2、xssScriptRegArr从配置读取用于防护扩展
 *
 */
public class XssCleanRuleUtils {

    private XssCleanRuleUtils() {

    }

    private static StringJoiner joiner = new StringJoiner("|");
    private static final String XSS_REPLACEMENT = "{XSS!}";
    private static Pattern xssPattern;
    private static final String[] xssScriptRegArr = {
            "<script>(.*?)</script>",
            "src[\r\n]*=[\r\n]*\\'(.*?)\\'",
            "</script>",
            "<script(.*?)>",
            "eval\\((.*?)\\)",
            "expression\\((.*?)\\)",
            "javascript:",
            "vbscript:",
            "onload(.*?)=",
            "<(.*?)>",
            "<iframe>(.*?)</iframe>",
            "on(load|error|mouseover|submit|reset|focus|click)(.*?)="
    };

    public static final List<String> XSS_REPLACEMENT_LIST = Collections.singletonList(XSS_REPLACEMENT);

    static {
        for (String reg : xssScriptRegArr) {
            joiner.add(reg);
        }

        xssPattern = Pattern.compile(joiner.toString(), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    }

    /**
     * isFind
     * @param value
     * @return
     */
    public static boolean isFind(String value) {
        if (!StringUtils.hasText(value)) {
            return false;
        }

        return xssPattern.matcher(value).find();
    }

    /**
     * xssClean
     * @param value
     * @return
     */
    public static String xssClean(String value) {
        if (!StringUtils.hasText(value)) {
            return value;
        }

        return xssPattern.matcher(value).replaceAll(XSS_REPLACEMENT);
    }

}
